package channel

import (
	"gitee.com/lipore/go-nio/pkg/buffer"
	"gitee.com/lipore/go-nio/pkg/frame"
)

type (
	InboundContext interface {
		Context
		InboundBuffer() *buffer.Buffer
		bindFrame(f frame.Frame)
		Frame() frame.Frame
	}
	InboundHandler interface {
		HandleInbound(ctx InboundContext) error
	}
)

type inboundContext struct {
	commonContext
	frame frame.Frame
}

func (i *inboundContext) bindFrame(f frame.Frame) {
	i.frame = f
}

func (i *inboundContext) Frame() frame.Frame {
	return i.frame
}

func (i *inboundContext) InboundBuffer() *buffer.Buffer {
	return i.channel.InboundBuffer()
}

func (i *inboundContext) Next() error {
	i.index++
	for i.index < int8(len(i.handlers)) {
		if h, ok := i.handlers[i.index].(InboundHandler); ok {
			err := h.HandleInbound(i)
			if err != nil {
				return err
			}
		}
		i.index++
	}
	return nil
}
